package com.netease.financial.base.lockpattern.patternunlock;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.netease.financial.R;
import com.netease.financial.base.lockpattern.LockPatternHelper;
import com.netease.financial.base.lockpattern.LockPatternPreferencesHelper;
import com.netease.financial.base.lockpattern.LockPatternUtils;
import com.netease.financial.base.lockpattern.LockPatternView;
import com.netease.financial.base.lockpattern.LockPatternView.Cell;
import com.netease.financial.common.security.SecurityJNI;
import com.netease.financial.common.util.NfsLog;
import com.netease.financial.common.util.PhoneNumberUtils;
import com.netease.financial.internal.di.components.DaggerPatternUnlockComponent;
import com.netease.financial.internal.di.components.PatternUnlockComponent;
import com.netease.financial.internal.di.modules.PatternUnlockModule;
import com.netease.financial.module.web.AccessToken;
import com.netease.financial.ui.activity.BaseAppCompatActivity;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;

import java.util.List;

import javax.inject.Inject;

public class PatternUnlockActivity extends BaseAppCompatActivity implements PatternUnlockView {

    private static final String TAG = PatternUnlockActivity.class.getSimpleName();

    private static final String INTENT_EXTRA_KEY_CLIENT_ID = "clientId";
    private static final String INTENT_EXTRA_KEY_HEAD_PORTRAIT_URL = "headPortraitUrl";
    private static final String INTENT_EXTRA_KEY_USER_ID = "userId";

    private static final int RESPONSE_CODE_AUTHENTICATION = 1;
    private static final int RESPONSE_CODE_RESET_LOCK_PATTERN = 2;

    private LockPatternView mLockPatternView;
    private int mFailedPatternAttemptsSinceLastTimeout = 0;
    private CountDownTimer mCountdownTimer = null;
    private Handler mHandler = new Handler();
    private TextView mHeadTextView;
    private TextView mClientIdTextView;
    private ImageView mHeadPortraitImageView;

    private Animation mShakeAnim;

    private Toast mToast;

    private String mClientId;
    private String mUserId;
    private String mHeadPortraitUrl;

    PatternUnlockComponent patternUnlockComponent;

    @Inject
    PatternUnlockPresenter patternUnlockPresenter;

    public static Intent getCallingIntent(Context context, String clientId, String headPortraitUrl, String userId) {
        Intent intent = new Intent(context, PatternUnlockActivity.class);
        intent.putExtra(INTENT_EXTRA_KEY_CLIENT_ID, clientId);
        intent.putExtra(INTENT_EXTRA_KEY_HEAD_PORTRAIT_URL, headPortraitUrl);
        intent.putExtra(INTENT_EXTRA_KEY_USER_ID, userId);

        intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        return intent;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_unlock_pattern);
        LockPatternHelper.registerIntoWhiteList(getClass().getName());

        handleIntent();
        initializeInjector();
        initialize();
    }

    private void initialize() {
        initViews();
        initialPresenter();
    }

    private void initializeInjector() {
        this.patternUnlockComponent = DaggerPatternUnlockComponent.builder()
                .applicationComponent(getApplicationComponent())
                .activityModule(getActivityModule())
                .patternUnlockModule(new PatternUnlockModule(new AccessToken(), SecurityJNI.getAppSecret()))
                .build();
        this.patternUnlockComponent.inject(this);
    }

    private void initialPresenter() {
        this.patternUnlockPresenter.setView(this);
        this.patternUnlockPresenter.initialize();
//        this.patternUnlockPresenter.checkAccessToken();
    }

    @Override
    protected boolean shouldShowChatBall() {
        return false;
    }

    @Override
    protected boolean shouldProtectedByLockPattern() {
        return false;
    }

    private void handleIntent() {
        mClientId = getIntent().getStringExtra(INTENT_EXTRA_KEY_CLIENT_ID);
        mHeadPortraitUrl = getIntent().getStringExtra(INTENT_EXTRA_KEY_HEAD_PORTRAIT_URL);
        mUserId = getIntent().getStringExtra(INTENT_EXTRA_KEY_USER_ID);
    }

    private void initViews() {
        initHeadPortrait();
        mLockPatternView = (LockPatternView) findViewById(R.id.gesturepwd_unlock_lockview);
        mLockPatternView.setOnPatternListener(mChooseNewLockPatternListener);
        mLockPatternView.setTactileFeedbackEnabled(true);
        mHeadTextView = (TextView) findViewById(R.id.gesturepwd_unlock_text);

        mClientIdTextView = (TextView) findViewById(R.id.clientId);
        mClientIdTextView.setText(PhoneNumberUtils.getPartHiddenNumber(mClientId));

        Button loginWithAnotherAccount = (Button) findViewById(R.id.gesturepwd_login_with_another_account);
        loginWithAnotherAccount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginWithAnotherAccount();

            }
        });
        Button forgetPassword = (Button) findViewById(R.id.gesturepwd_unlock_forget);
        forgetPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String nextTip = getString(R.string.next_prompt);
                getNavigator().navigateToAuthenticationScreen(PatternUnlockActivity.this, mClientId, mHeadPortraitUrl, mUserId, nextTip, RESPONSE_CODE_AUTHENTICATION);
            }
        });

        mShakeAnim = AnimationUtils.loadAnimation(this, R.anim.shake_x);

        mFailedPatternAttemptsSinceLastTimeout = LockPatternPreferencesHelper.getFailedAttemptsSinceLastTimeout();
        if (mFailedPatternAttemptsSinceLastTimeout >= LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT) {
            mHandler.postDelayed(attemptLockout, 0);
        }
    }

    private void loginWithAnotherAccount() {
        // clear current user data
        LockPatternHelper.setUserId("");
        // go to login page
        getNavigator().loginWithOtherAccount(this);
        PatternUnlockActivity.this.mClientIdTextView.postDelayed(new Runnable() {
            @Override
            public void run() {
                PatternUnlockActivity.this.finish();
            }
        }, 100);
    }

    private void initHeadPortrait() {
        mHeadPortraitImageView = (ImageView) findViewById(R.id.gesturepwd_unlock_face);

        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.ic_user_head_portrait_default)
                .showImageForEmptyUri(R.drawable.ic_user_head_portrait_default)
                .showImageOnFail(R.drawable.ic_user_head_portrait_default)
                .resetViewBeforeLoading(false)  // default
                .delayBeforeLoading(0)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default
                .bitmapConfig(Bitmap.Config.ARGB_8888)              // default
                .displayer(new SimpleBitmapDisplayer()) // default 可以设置动画，比如圆角或者渐变
                .handler(new Handler())                             // default
                .build();

        ImageLoader.getInstance().displayImage(mHeadPortraitUrl, mHeadPortraitImageView, options);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (!shouldShowLockPattern()) {
            finish();
        }

    }

    public boolean shouldShowLockPattern() {
        if (TextUtils.isEmpty(mUserId)) {
            NfsLog.d(TAG, "userId is empty");
            return false;
        }
        if (!LockPatternHelper.isLoginTimeOut()) {
            NfsLog.d(TAG, "not need pattern lock");
            return false;
        }

        return LockPatternHelper.isLockPatternExistsForUser(mUserId);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCountdownTimer != null) {
            mCountdownTimer.cancel();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        NfsLog.d(TAG, "requestCode:" + requestCode);
        NfsLog.d(TAG, "resultCode:" + resultCode);
        if (handleAuthenticationResult(requestCode, resultCode, data)) {
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private boolean handleAuthenticationResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RESPONSE_CODE_AUTHENTICATION:
                    getNavigator().navigateToCreateLockPatternScreen(this, mUserId, RESPONSE_CODE_RESET_LOCK_PATTERN);
                    return true;
                case RESPONSE_CODE_RESET_LOCK_PATTERN:
                    finish();
                    return true;
            }
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        // Forbid user to go back
    }

    private void showToast(CharSequence message) {
        if (null == mToast) {
            mToast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
            mToast.setGravity(Gravity.CENTER, 0, 0);
        } else {
            mToast.setText(message);
        }

        mToast.show();
    }

    private Runnable mClearPatternRunnable = new Runnable() {
        public void run() {
            mLockPatternView.clearPattern();
        }
    };

    protected LockPatternView.OnPatternListener mChooseNewLockPatternListener = new LockPatternView.OnPatternListener() {

        public void onPatternStart() {
            mLockPatternView.removeCallbacks(mClearPatternRunnable);
            patternInProgress();
        }

        public void onPatternCleared() {
            mLockPatternView.removeCallbacks(mClearPatternRunnable);
        }

        public void onPatternDetected(List<Cell> pattern) {
            if (pattern == null) {
                return;
            }
            if (LockPatternHelper.checkPattern(pattern, mUserId)) {
                mLockPatternView.setDisplayMode(LockPatternView.DisplayMode.Correct);
                showToast("解锁成功");
                LockPatternHelper.unlockForUser(mUserId);
                finish();
            } else {
                mLockPatternView.setDisplayMode(LockPatternView.DisplayMode.Wrong);
                if (pattern.size() >= LockPatternUtils.MIN_PATTERN_REGISTER_FAIL) {
                    mFailedPatternAttemptsSinceLastTimeout++;
                    LockPatternPreferencesHelper.setFailedAttemptsSinceLastTimeout(mFailedPatternAttemptsSinceLastTimeout);
                    int retry = LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT - mFailedPatternAttemptsSinceLastTimeout;
                    if (retry >= 0) {
                        if (retry == 0) {
                            showToast("您已" + mFailedPatternAttemptsSinceLastTimeout + "次输错密码，请30秒后再试");
                        } else {
                            //                        mHeadTextView.setText("密码错误，还可以再输入" + retry + "次");
                            String errorPasswordText = getString(R.string.lock_pattern_error_password_text);
                            mHeadTextView.setText(String.format(errorPasswordText, retry));
                            mHeadTextView.startAnimation(mShakeAnim);
                        }
                    }

                } else {
                    showToast("输入长度不够，请重试");
                }

                if (mFailedPatternAttemptsSinceLastTimeout >= LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT) {
                    LockPatternPreferencesHelper.setFailedAttemptTimeoutMillis(LockPatternUtils.FAILED_ATTEMPT_TIMEOUT_MS + 1);
                    mHandler.postDelayed(attemptLockout, 2000);
                } else {
                    mLockPatternView.postDelayed(mClearPatternRunnable, 2000);
                }
            }
        }

        public void onPatternCellAdded(List<Cell> pattern) {

        }

        private void patternInProgress() {
        }
    };

    Runnable attemptLockout = new Runnable() {

        @Override
        public void run() {
            mLockPatternView.clearPattern();
            mLockPatternView.setEnabled(false);
            long millisInFuture = LockPatternPreferencesHelper.getFailedAttemptTimeoutMillis();
            mCountdownTimer = new CountDownTimer(millisInFuture, 1000) {

                @Override
                public void onTick(long millisUntilFinished) {
                    LockPatternPreferencesHelper.setFailedAttemptTimeoutMillis(millisUntilFinished);
                    int secondsRemaining = (int) (millisUntilFinished / 1000) - 1;
                    if (secondsRemaining > 0) {
                        mHeadTextView.setText(secondsRemaining + " 秒后重试");
                    } else {
                        mHeadTextView.setText(R.string.lock_pattern_draw_gesture_password_text);
                        mHeadTextView.setTextColor(Color.WHITE);
                    }

                }

                @Override
                public void onFinish() {
                    mLockPatternView.setEnabled(true);
                    mFailedPatternAttemptsSinceLastTimeout = 0;
                    LockPatternPreferencesHelper.setFailedAttemptsSinceLastTimeout(0);
                    LockPatternPreferencesHelper.setFailedAttemptTimeoutMillis(0);
                }
            }.start();
        }
    };

    @Override
    public void showAccessTokenInvalidView() {
//        loginWithAnotherAccount();
    }

}
